package com.jgp.security.shiro.component;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-12-11
 */
public class JGPWebSessionManager extends DefaultWebSessionManager {
    
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = WebUtils.toHttp(request).getHeader("Authorization");
        String sessionId = null;
        if(StringUtils.isNotBlank(token)&&token.startsWith("JGPSESSIONID")){
            sessionId = token.replace("JGPSESSIONID=","");
        }
        if(StringUtils.isBlank(token)){
            sessionId = WebUtils.toHttp(request).getParameter("JGPSESSIONID");
        }
        if(StringUtils.isNotBlank(sessionId)){
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,"url");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return sessionId;
        }
        return super.getSessionId(request, response);
    }
}
